<template>
  <div class="locateQuery">
    <Row :gutter="8" style="height: 100%;">
      <Col class="gutter-row list" :span="6">
        <Card  dis-hover :bordered="true" style="height: 280px;">
          <template #title>搜索</template>
          <Form ref="formSearch" style="width: 100%" :model="formDataSearch" label-position="top">
            <Row :gutter="8">
              <Col :span="12">
                <FormItem label="车牌号">
                  <i-input v-model="formDataSearch.carPlateNo" placeholder="请输入车牌号码" clearable/>
                </FormItem>
              </Col>
              <Col :span="12">
                <FormItem label="车牌颜色">
                  <Select v-model="formDataSearch.carPlateColor">
                    <Option v-for="item in colorList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <FormItem label="定位周期">
              <RadioGroup v-model="formDataSearch.stepSize" type="button" button-style="solid" @change="cycleChange">
                <Radio :label="1">1分钟</Radio>
                <Radio :label="3">3分钟</Radio>
                <Radio :label="5">5分钟</Radio>
                <Radio :label="7">7分钟</Radio>
                <Radio :label="9">9分钟</Radio>
                <Radio :label="12">12分钟</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="searchSubmit" long :disabled="isSearch">搜索</Button>
            </FormItem>
          </Form>
        </Card>
        <Card dis-hover :bordered="true" style="height: calc(100% - 288px);overflow: hidden;margin-top: 8px">
          <template #title>车辆列表</template>
          <xdTable ref="xdTableRef" :tableData="tableData"></xdTable>
        </Card>
      </Col>
      <Col class="gutter-row" :span="18">
        <div style="height: 100%">
          <Card dis-hover :bordered="true" style="height: calc(100% - 268px);overflow: hidden;" :padding="6">
            <div id="xd_map" style="width: 100%;height: 100%;"></div>
          </Card>
          <div style="height: 260px;margin-top: 6px;">
            <Row :gutter="8">
              <Col :span="15">
                <Card dis-hover :bordered="true" style="height: 100%;" :padding="6">
                  <div class="data-g-view">
                    <div class="data-cell">
                      <div class="data-key">车牌号码</div>
                      <div class="data-value" style="font-weight: bold">{{ carInfo.carPlateNo }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">车架号</div>
                      <div class="data-value">{{ carInfo.frameNo }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">发动机号</div>
                      <div class="data-value">{{ carInfo.vehicleEngineNo }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">燃料类型</div>
                      <div class="data-value">{{ carInfo.fuelType }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">排放标准</div>
                      <div class="data-value">{{ carInfo.vehicleEmissionStandards }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">车辆类型</div>
                      <div class="data-value">{{ carInfo.vehicleType }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">车辆品牌</div>
                      <div class="data-value">{{ carInfo.vehicleBrand }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">车辆型号</div>
                      <div class="data-value">{{ carInfo.vehicleModel }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">运输证号</div>
                      <div class="data-value">{{ carInfo.vehicleOperationCertificateNo }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">运营企业</div>
                      <div class="data-value">{{ carInfo.deptName }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">车主/业户</div>
                      <div class="data-value">{{ carInfo.vehicleOwnerName }} {{ carInfo.vehicleOwnerPhone }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">所属地区</div>
                      <div class="data-value">{{ carInfo.provinceName }}{{ carInfo.cityName }}{{ carInfo.countyName }}</div>
                    </div>
                  </div>
                </Card>
              </Col>
              <Col :span="9">
                <Card dis-hover :bordered="true" style="height: 100%" :padding="6">
                  <div class="data-g-view" style="grid-template-columns:1fr;">
                    <div class="data-cell">
                      <div class="data-key">定位时间</div>
                      <div class="data-value">{{ currentData.dateTime }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">最新位置</div>
                      <div class="data-value">{{ currentData.location }}</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">当前总里程</div>
                      <div class="data-value" v-if="currentData.vec3 || currentData.vec3 == 0">{{ currentData.vec3 }}km</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">当前速度</div>
                      <div class="data-value" v-if="currentData.vec1 || currentData.vec1 == 0">{{ currentData.vec1 }}km/h</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">ACC状态</div>
                      <div class="data-value" v-if="currentData.acc == 0">关闭</div>
                      <div class="data-value" v-if="currentData.acc == 1">打开</div>
                    </div>
                    <div class="data-cell">
                      <div class="data-key">方向</div>
                      <div class="data-value">{{ currentData.directionName }}</div>
                    </div>
                  </div>
                </Card>
              </Col>
            </Row>
          </div>
        </div>
      </Col>
    </Row>
  </div>
</template>
<script setup>
import {inject, reactive, ref, resolveComponent, nextTick, onMounted, onUnmounted} from 'vue'
const apiUrl = inject('$apiUrl') //接口调用
const $axios = inject('$axiosInterceptor');// 变量全局化 axios
import xdTable from '@/components/table/index.vue'
const $ViewUIPlus = inject('$ViewUIPlus');//引用全局组件
import b1 from '@/assets/track/b_1.png'
const $echarts = inject('$echarts');//自己封装的方法

onMounted (() => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")
  mapLoad();
  // initCharts();
})

onUnmounted(() => {
  clearTimer()
})

const formDataSearch = ref({
  carPlateNo:'',
  carPlateColor:'2',
  stepSize:3
})

/**
 * 车牌颜色
 */
const colorList = [
  {
    value: '2',
    label: '黄色'
  },
  {
    value: '1',
    label: '蓝色'
  },
  {
    value: '5',
    label: '绿色'
  },
  {
    value: '95',
    label: '黄绿色'
  }
]

/**
 * 车辆定位列表
 * @type {Ref<UnwrapRef<*[]>>}
 */
const carList = ref([])

/**
 * 车辆信息列表
 * @type {Ref<UnwrapRef<*[]>>}
 */
const carInfoList = ref([])

/**
 * 车辆信息
 * @type {Ref<UnwrapRef<*[]>>}
 */
const carInfo = ref({})

/**
 * 车辆定位点列表
 * @type {Ref<UnwrapRef<*[]>>}
 */
const markerList = ref([])

/**
 * 车辆轨迹列表
 * @type {Ref<UnwrapRef<*[]>>}
 */
const polylineList = ref([])

/**
 * 是否正在搜索
 * @type {Ref<UnwrapRef<boolean>>}
 */
const isSearch = ref(false)

/**
 * 当前在地图上显示的车辆
 */
const currentData = ref({})

// table
const xdTableRef = ref();
const tableData = reactive({
  url: "",//请求地址
  method: 'post',//请求方式
  where: {},//搜索条件
  dataList:carList,
  height: '100%',//表格高度 auto
  page: false,//分页是否使用
  pageSize:'small',//大 big 小 small false
  columns: [//表头数据
    {type: 'index', width: 50, align: 'center', title: '序号'},
    {title: "车牌号", key: "carPlateNo", width: 120, align: "center", render: (h, params) => {
        var color = "",textColor = '';
        if (params.row.carPlateColor == 1) {//蓝色
          textColor = '#fff', color = "#2179fc";
        } else if (params.row.carPlateColor == 2) {//黄色
          textColor = '#333', color = "#fac808";
        } else if (params.row.carPlateColor == 3) {//黑色
          textColor = '#fff', color = "#515a6e";
        } else if (params.row.carPlateColor == 4) {//白色
          textColor = '#333', color = "#ffffff";
        } else if (params.row.carPlateColor == 5) {//绿色
          textColor = '#333', color = "#86f80a";
        } else if (params.row.carPlateColor == 93) {//黄绿色
          textColor = '#333', color = "#8ebe19";
        } else if (params.row.carPlateColor == 9) {//其他
          textColor = '#333', color = "blue";
        } else {
          textColor = '#333', color = "blue";
        }
        return h('span',{
          style: { "cursor": "pointer",display: 'flex',justifyContent: 'center',}},[
          h('div',{style:{padding:'3px',width:'100px',height:'36px',borderRadius:'3px',color:textColor,background: color + '8A',border:`1.5px solid ${color}`,}},[
            h("div",{style:{fontSize:'15px',fontWeight:'600',color:textColor,background: color,height:'100%',borderRadius:'3px',display: 'flex',justifyContent: 'center', alignItems:'center',}}, params.row.carPlateNo)
          ]),
        ],)
      }
    },
    {title: "在线状态", key: "chn", align: "center", render: (h, params) => {
        if (params.row.isOnline) {//在线
          return h(resolveComponent('Tag'), {type: 'dot',color: 'success'}, '在线');
        }else  {//黄色
          return h(resolveComponent('Tag'), {type: 'dot',color: 'error'}, '离线');
        }
      }
    },
    {
      title: '操作', width: 80, fixed: 'right', render: (h, params) => {
        var operationButtons = [];
        operationButtons.push(
            h('span', {
              style: { "color": "#e54d42", "cursor": "pointer"},
              onClick: () => {
                $ViewUIPlus.Modal.confirm({
                  title: '删除提醒',
                  content: '确定要删除选中的车辆吗？',
                  onOk: () => {
                    deleteCar(params.index)
                  },
                  onCancel: () => {
                    //点击取消
                  }
                })
              }
            }, '删除')
        )
        return operationButtons;
      }
    }
  ],
  pagingParameters:{// 分页参数
    page:'pageNo',
    limit:'pageSize'
  },
  format: {//返回数据格式
    list: ['data'],//数据list
    count: ['count'],//数据总量
  },
  onCurrentChange:(currentRow, oldCurrentRow)=>{
    currentData.value = currentRow
    //切换地图中心视角
    let index = findCarInfo(currentRow)
    if(index != -1){
      carList.value.map(item =>{
        delete item._highlight
      })
      carList.value[index]._highlight = true
      carInfo.value = carInfoList.value[index]
      state.map.setZoom(15)
      setTimeout(() => {
        state.map.setCenter(new BMap.Point(currentRow.lonX, currentRow.latY))
      },200)
    }
  }
})

/**
 * 删除车辆
 * @param index
 */
const deleteCar = (index) => {

  //删除对应的marker
  state.map.removeOverlay(markerList.value[index])
  //删除对应的轨迹
  state.map.removeOverlay(polylineList.value[index])

  carList.value.splice(index,1)
  carInfoList.value.splice(index,1)
  markerList.value.splice(index,1)
  polylineList.value.splice(index,1)

  if(carList.value.length <= 0){
    clearTimer()
  }
}

//搜索
const searchSubmit = () => {
  let data = JSON.parse(JSON.stringify(formDataSearch.value));
  //判断查询的车牌号是否在列表已经存在
  let carInfo = carList.value.find(res => res.carPlateColor == data.carPlateColor && res.carPlateNo == data.carPlateNo)
  if(carInfo){
    $ViewUIPlus.Message.warning(`${data.carPlateNo}已存在，请勿重复搜索`);
    return
  }
  checkCarInfo()
}

/**
 * 检查车辆信息，是否入网、是否本籍的车
 */
const checkCarInfo = () => {
  let msg = $ViewUIPlus.Message.loading({
    content: '定位查询中...',
    duration: 0
  });
  isSearch.value = true
  $axios.post(apiUrl.coreVehicleCoreVehicleInfo,formDataSearch.value).then((res) => {
    let data = res.data.data
    if(!data){
      msg()
      $ViewUIPlus.Message.warning("未查询到车辆信息")
      isSearch.value = false
      return
    }else if(data.internetState != 1){
      msg()
      $ViewUIPlus.Message.warning("车辆未入网无法查询轨迹")
      isSearch.value = false
      return
    }
    getPosition(msg,data)
  }).catch((err) => {
    isSearch.value = false
    msg()
  })
}

/**
 * 获取定位信息
 */
const getPosition = (msg,data) => {
  isSearch.value = true
  $axios.post(apiUrl.positionInfo,formDataSearch.value).then((res) => {
    isSearch.value = false
    msg()
    //一下这三个列表需要一一对应，一个删都得删
    carList.value.map(item =>{
      delete item._highlight
    })
    carList.value.push(Object.assign({_highlight:true},res.data.data))
    carInfoList.value.push(data)
    markerList.value.push(null)
    polylineList.value.push(null)
    currentData.value = res.data.data
    carInfo.value = data
    addMarker(res.data.data)

    startTimer()
  }).catch((err) => {
    isSearch.value = false
    msg()
  })
}

/**
 * 定时器
 */
const timer = ref(null)

/**
 * 定位周期的变化
 */
const cycleChange = () => {
  startTimer()
}

/**
 * 开启定时器
 */
const startTimer = () => {
  clearTimer()
  timer.value = setInterval(() => {
    getPositionInfo()
  },60 * 1000 * formDataSearch.value.stepSize)
}

/**
 * 清理定时器
 */
const clearTimer = () => {
  if(timer.value){
    clearInterval(timer.value)
    timer.value = null
  }
}

/**
 * 获取车辆定位信息
 */
const getPositionInfo = () => {
  carList.value.forEach(data => {
    $axios.post(apiUrl.positionInfo,data).then((res) => {
      addMarker(res.data.data)
    }).catch((err) => {
    })
  })
}

/**
 * 根据车牌号查询下标
 */
const findCarInfo = (data) => {
  let index = -1
  for (let i = 0; i < carList.value.length; i++) {
    let carInfo = carList.value[i]
    if(carInfo.carPlateNo == data.carPlateNo && carInfo.carPlateColor == data.carPlateColor){
      index = i
      break
    }
  }
  return index
}

/**
 * 添加定位点
 */
const addMarker = (data) => {

  let myIcon = new BMap.Icon(b1, new BMap.Size(22, 22));
  let index = findCarInfo(data)
  //如果没找到，则表明数据有问题啦，正常情况是不可能不存在的
  if( index == -1){
    return
  }
  //更新车辆上的定位信息
  carList.value[index].lonX = data.lonX
  carList.value[index].latY = data.latY
  carList.value[index].isOnline = data.isOnline
  //删除上一个marker
  if(markerList.value[index]){
    state.map.removeOverlay(markerList.value[index])
  }

  let marker = new BMap.Marker(new BMap.Point(data.lonX, data.latY), {icon: myIcon,id:2});  // 创建标注
  marker.setRotation(data.direction);
  marker.setZIndex(999999);
  // let html = '<div style=\'background:#FFFFFF;color:#000000;font-weight:normal;padding: 1px;border:solid  1px #ccc\'>' +
  //     '<div>行驶速度：' + data.vec1 + ' / ' + data.vec2 + '</div>' +
  //     '<div>总里程数：' + data.vec3 + '公里</div>' +
  //     '<div>行驶状态： ' + ((data.state >> 0 & 1) ? '启动' : '熄火') + ((data.state >> 1 & 1) ? ' - 定位' : ' - 未定位') + '</div>' +
  //     '<div>报警状态： ' + ((data.alarm >> 1 & 1) ? '超速报警' : "无超速") + ((data.alarm >> 2 & 1) ? '-疲劳报警' : " - 无疲劳") + '</div>' +
  //     '<div>定位时间：' + data.dateTime + '</div>' +
  //     '</div>';
  // let BaiMakerLabel = new BMap.Label(html, {offset: new BMap.Size(22, -3)});
  // BaiMakerLabel.setStyle({border: 'none', padding: '3px 5px', background: 'none'});
  // marker.setLabel(BaiMakerLabel);
  //增加点
  state.map.addOverlay(marker);
  if(currentData.value.carPlateNo == data.carPlateNo && currentData.value.carPlateColor == data.carPlateColor){
    currentData.value = data
    state.map.setZoom(15)
    setTimeout(() => {
      state.map.setCenter(new BMap.Point(data.lonX, data.latY))
    },200)
  }

  //更新车辆的marker
  markerList.value[index] = marker

  //向车辆的轨迹中增加新的坐标点,如果是空的轨迹就新建，不为空就往里塞值
  if(carList.value[index].trajectory){
    carList.value[index].trajectory.push([data.lonX, data.latY])
  }else{
    carList.value[index].trajectory = [[data.lonX, data.latY]]
  }

  //更新车辆的轨迹信息
  if(carList.value[index].trajectory.length > 1){
    if(polylineList.value[index]){
      state.map.removeOverlay(polylineList.value[index])
    }
    let line = []
    carList.value[index].trajectory.forEach(item => {
      line.push(new BMap.Point(item[0], item[1]))
    })
    let polyline = new BMap.Polyline(line, {
      strokeWeight: 2,//折线的宽度，以像素为单位
      strokeOpacity: 0.8,//折线的透明度，取值范围0 - 1
      strokeColor: "#1890ff" //折线颜色
    });
    polylineList.value[index] = polyline
    state.map.addOverlay(polyline);
  }
}

const myChart = ref(null)
/**
 * 初始化图表
 */
const initCharts = () => {
  let chartDom = document.getElementById('gaugeCharts');
  myChart.value = $echarts.init(chartDom);
  let option = {
    grid: [
      {
        bottom: '10px',
        left:"10px",
        top:"10px",
        right:"10px"
      }
    ],
    series: [
      {
        type: 'gauge',
        axisLine: {
          lineStyle: {
            width: 30,
            color: [
              [0.3, '#67e0e3'],
              [0.7, '#37a2da'],
              [1, '#fd666d']
            ]
          }
        },
        pointer: {
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          distance: -30,
          length: 8,
          lineStyle: {
            color: '#fff',
            width: 2
          }
        },
        splitLine: {
          distance: -30,
          length: 30,
          lineStyle: {
            color: '#fff',
            width: 4
          }
        },
        axisLabel: {
          color: 'inherit',
          distance: 40,
          fontSize: 12
        },
        detail: {
          valueAnimation: true,
          formatter: '{value} km/h',
          color: 'inherit',
          fontSize: 12
        },
        data: [
          {
            value: 0
          }
        ]
      }
    ]
  };
  option && myChart.value.setOption(option);
}

//地图
//地图加载
const state = reactive({
  formData: {},
  trackData:{},
  positionTrajectory:[],//车辆定位数据
  trackSearchData: {},//轨迹搜索数据
  map: null,//地图
});

const mapLoad = ()=> {
  state.map = new BMap.Map("xd_map");    // 创建Map实例
  state.map.centerAndZoom(new BMap.Point(105.058886,36.028623), 4);  // 初始化地图,设置中心点坐标和地图级别
  //添加地图类型控件
  state.map.addControl(new BMap.MapTypeControl({
    mapTypes: [
      BMAP_NORMAL_MAP,
      BMAP_HYBRID_MAP
    ]
  }));
  state.map.setCurrentCity("邢台");          // 设置地图显示的城市 此项是必须设置的
  state.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
  // 左上角，添加比例尺
  let top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});
  state.map.addControl(top_left_control);
  //左上角，添加默认缩放平移控件
  let top_left_navigation = new BMap.NavigationControl();
  state.map.addControl(top_left_navigation);
}

</script>
<style lang="less">
.locateQuery{
  padding: 10px;
  height: 100%;
  .ivu-card-body {
    height: 100% ;
  }
  .list{
    .ivu-card-body {
      height: calc(100% - 51px);
    }
  }

  .data-g-view{
    background-color: rgba(0,0,0,0.13);
    padding: 1px;
    display: grid;
    grid-template-columns:1fr 1fr;
    grid-gap: 1px 1px;
  }

  .data-cell{
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 40px;
    background-color: #ffffff;
    font-size: 13px;

    .data-key{
      width: 82px;
      height: 100%;
      line-height: 40px;
      text-align: center;
      background-color: #f4f4f4;
    }
    .data-value{
      flex: 1;
      height: 100%;
      padding-left: 20px;
      line-height: 40px;
    }
  }
}
</style>
